<?php

namespace backend\controllers;

use backend\models\PayUserDiscount;
use Yii;
use backend\models\SysUserDesigner;
use backend\models\SysUserDesignerSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;
use common\models\UserInfo;
use yii\web\ForbiddenHttpException;
use liangzoe\mobilesmser\TextSmser;
use backend\models\UserInvite;
use yii\db\ActiveRecord;
use frontend\models\UserInfoEx;
use backend\models\PrfConfig;
use backend\models\LogUserScore;
use backend\models\User;
use backend\models\LogPayVip;
use backend\models\UserPayVip;
use backend\models\VipRefund;
use backend\models\PayTradeRebate;
use backend\models\LogVipContinue;

/**
 * SysUserDesignerController implements the CRUD actions for SysUserDesigner model.
 */
class SysUserDesignerController extends Controller
{
    /**
     * @inheritdoc
     */
    private $res = ['code' => 0, 'msg' => '', 'data' => null];

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                    'bulk-delete' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
        //如果未登录，则直接跳转
        if (Yii::$app->user->isGuest) {
            return $this->redirect(['/site/login']);
        }


        $action = Yii::$app->controller->action->id;
        $controller = Yii::$app->controller->id;
        if (\Yii::$app->user->can('user-designer')) {
            return true;
        } else {
            throw new ForbiddenHttpException(Yii::t('app', 'Sorry , You don\'t have permission'));
        }
    }

    /**
     * Lists all SysUserDesigner models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SysUserDesignerSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, false, "");

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }


    /**
     * Displays a single SysUserDesigner model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $request = Yii::$app->request;
        if ($request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                'title' => Yii::t('app', "Sys User Designers View"),
                'content' => $this->renderPartial('view', [
                    'model' => $this->findModel($id),
                ]),
                'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                    Html::a('Edit', ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
            ];
        } else {
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }
    }

    /**
     * Creates a new SysUserDesigner model.
     * For ajax request will return json object
     * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $request = Yii::$app->request;
        $model = new SysUserDesigner();

        if ($request->isAjax) {
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($request->isGet) {
                return [
                    'title' => "Create new SysUserDesigner",
                    'content' => $this->renderPartial('create', [
                        'model' => $model,
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                        Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])

                ];
            } else if ($model->load($request->post()) && $model->save()) {
                return [
                    'forceReload' => 'true',
                    'title' => "Create new SysUserDesigner",
                    'content' => '<span class="text-success">Create SysUserDesigner success</span>',
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                        Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])

                ];
            } else {
                return [
                    'title' => "Create new SysUserDesigner",
                    'content' => $this->renderPartial('create', [
                        'model' => $model,
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                        Html::button('Save', ['class' => 'btn btn-primary', 'type' => "submit"])
                ];
            }
        } else {
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->uid]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }

    }

    /**
     * Updates an existing SysUserDesigner model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
       
        $request = Yii::$app->request;
        $model = $this->findModel($id);
        $model->setScenario('update');
        if ($request->isAjax) {
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($request->isGet) {
                return [
                    'title' => Yii::t('app', "Sys User Designers"),
                    'content' => $this->renderPartial('update', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                        Html::button('Save', ['class' => 'btn btn-primary', 'id' => 'designer_audit_btn', 'type' => "submit"])
                ];
            } else if ($model->load($request->post())) {
                
                $user_typeclass=1;
                $model_user = UserInfo::findOne(['id' => $id]);
                $loy_pay=LogPayVip::find ()->where(['uid'=>$id,'state'=>2])->orderBy("starttime desc")->limit(1)->one();
                //根据Log_pay_vip获取充值的用户类型  1普通会员 5超级会员
                if($loy_pay){
                    $user_typeclass=intval($loy_pay->user_type_class);
                }
                if ($request->post() !== null && $request->post('SysUserDesigner') !== null && isset($request->post('SysUserDesigner')['audit_state'])) {

                    $model->audit_time = time();
                    $model->audit_uid = Yii::$app->user->id;
                    $model->audit_state = $request->post('SysUserDesigner')['audit_state'];
                    if ($request->post('SysUserDesigner')['audit_state'] == 1) {//审核通过
                        $this->_invite_code($id);
                        //送积分
                        $logUserScore_mod = new LogUserScore();
                        $logUserScore_mod->designerPoint($id,$user_typeclass);
                    }
                }
                //插入付费用户会员到期时间表（1年）。
                if ($model->save()) {
                    ///删除user_info_ex的邀请码数据
                    $invite_f_info = UserInfoEx::findOne(['user_id' => $id, 'u_key' => 'invite_f']);
                    if ($invite_f_info)
                        $invite_f_info->delete();
                 
                    //审核通过   lwx 8/27  修改手动审核
                    if ($model->audit_state == 1) {
                        //新增user_pay_vip表
                        $user_pay_vip=new UserPayVip();
                        $user_pay_vip->user_id=$model->uid;
                        $user_pay_vip->start_time=time();
                        $user_pay_vip->end_time=time()+ 365 * 24 * 60 * 60 ;
                      
                        //超级VIP 更新用户的用户级别为5（user_type_class=5）
                        if($user_typeclass==5){
                            $user_pay_vip->user_type_class=5;
                            $model_user->user_type_class=5;
                        }else{
                            $user_pay_vip->user_type_class=1;
                            $model_user->user_type_class=1;
                        } 
                        $user_pay_vip->save();
                        $model_user->user_type = '3';
                        $message = "您在JAJAHOME平台申请的VIP会员已通过！客服电话：400-690-3766";
                    }
                    if ($model->audit_state == 2) {
                        //审核未通过，发起退款，通知财务
                        if($loy_pay){
                            $refund_model = new VipRefund();
                            $refund_model->rmb = round($loy_pay->rmb , 2);//退款金额
                            $refund_model->refund_no = date('YmdHis',time()).time().rand(10, 99);
                            $refund_model->doing = 3;
                            $refund_model->done_list = "vip审核未通过自动发起退款|".Yii::$app->user->identity->username.
                            "(".Yii::$app->user->identity->id.")|".date('Y-m-d H:i:s',time());
                            $refund_model->transaction_id = str_replace(['wx','zfb_'], ['',''], $loy_pay->transaction_id);
                            $refund_model->trade_no =$loy_pay->trade_no;
                            $refund_model->uid =$loy_pay->uid;
                            $refund_model->type =$loy_pay->type;//退款的方式与付款方式一样
                            $refund_model->state =1;
                            $refund_model->memo_xml ='';
                            $refund_model->addtime = time();
                            $result = $refund_model->save();
                            //发起退款，通知财务
                            if($result){
                                
                                $smser = new TextSmser();
                                $tel_list=Yii::$app->params['sms_tel'];
                                $refund_msg=$model->name.'的VIP审核未通过，请去退款页面确认并进行退款。';
                                foreach($tel_list as $cw){
                                    $smser->sendSMS($cw, $refund_msg);
                                }
                            }
                            $model_user->user_type = '1';
                            $model_user->user_type_class=1;
                            $message = "您的VIP会员申请未通过，原因是：" . $model->audit_memo;
                        }
                    }
                    if ($model_user->save()) {
                        $mobile = $model_user->tel;
                        $smser = new TextSmser();
                        $smser->sendSMS($mobile, $message);
                        //返点
                        $model_user = UserInfo::findOne(['id' => $id]);
                        //9/16  给上级返点   prf_config 一级返点: VIP_rebate_class_1  二级返点: VIP_rebate_class_2
                        if($loy_pay){
                            $pay_trade_rebate_model=new PayTradeRebate();
                            $result=$pay_trade_rebate_model->add_rebate_prev($id);
                        }
                        
                        
                    }
                    return [
                        'forceReload' => 'true',
                        'title' => Yii::t('app', "Sys User Designers View"),
                        'content' => $this->renderPartial('view', [
                            'model' => $this->findModel($id),
                        ]),
                        'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                            Html::a('Edit', ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
                    ];
                }
            } else {
                return [
                    'title' => Yii::t('app', "Sys User Designers"),
                    'content' => $this->renderPartial('update', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
                        Html::button('Save', ['class' => 'btn btn-primary', 'id' => 'designer_audit_btn', 'type' => "submit"])
                ];
            }
        } else {
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->uid]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
    }

    public function actionChangeInvite()
    {
       
        if (\Yii::$app->user->can('user-invite-change')) {
            return $this->render('change_invite', [
                'model' => null
            ]);
        }else{
            throw new ForbiddenHttpException(Yii::t('app', 'Sorry , You don\'t have permission'));
        }
    }

    /**
     * 搜索邀请码
     * @return array
     */
    public function actionSearchInvite()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        if (\Yii::$app->user->can('user-invite-change')) {
            if (Yii::$app->request->isPost) {
                $model = new UserInvite();
                $params = Yii::$app->request->post();
                $info = $model->getByUidOrPhone($params['uid'], $params['tel']);
                if ($info == null) {
                    $this->res['code'] = -1;
                    $this->res['msg'] = $model->_error;
                } else {
                    $this->res['data'] = ['uid' => $info['uid'], 'tel' => $info['tel'], 'nickname' => $info['nickname'], 'oldInvite' => $info['invite'],'invite_tel'=>$info['invite_tel'],'invite_uid'=>$info['invite_uid'],'invite_code'=>$info['invite_code']];
                }
            }
        } else {
            $this->res['code'] = -1;
            $this->res['msg'] = Yii::t('app', 'Sorry , You don\'t have permission');
        }
        return $this->res;
    }

    public function actionInviteOldToNew()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        if (\Yii::$app->user->can('user-invite-change')) {
            if (Yii::$app->request->isPost) {
                $params = Yii::$app->request->post();
                $model = new UserInvite();
                if($model->changeInviteOld2New($params['uid'], $params['oldInvite'], $params['newInvite'])){
                    $this->res['msg'] = '邀请码修改成功';
                    $this->res['data'] = $params;
                }else{
                    $this->res['code'] = -1;
                    $this->res['msg'] = $model->_error;
                }
            }
        }  else {
            $this->res['code'] = -1;
            $this->res['msg'] = Yii::t('app', 'Sorry , You don\'t have permission');
        }
        return $this->res;
    }

    //补充邀请码
    public function _invite_code($id)
    {
        $invite_info = UserInvite::findOne($id);
        if (!$invite_info || ($invite_info && !$invite_info['invite'])) {
            $invite_f_info = UserInfoEx::findOne(['user_id' => $id, 'u_key' => 'invite_f']);
            if ($invite_f_info) {
                $new_invite = new UserInvite();
                $new_invite->setScenario('update');
                $new_invite->uid = $id;
                $new_invite->invite = TextSmser::random_mix(6);
                $new_invite->invite_f = $invite_f_info['u_value'];
                $new_invite->save();
            }
        }
    }

    /**
     * Delete an existing SysUserDesigner model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $request = Yii::$app->request;
        $this->findModel($id)->delete();

        if ($request->isAjax) {
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose' => true, 'forceReload' => true];
        } else {
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }


    }

    /**
     * Delete multiple existing SysUserDesigner model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionBulkDelete()
    {
        $request = Yii::$app->request;
        $pks = $request->post('pks'); // Array or selected records primary keys
        foreach (SysUserDesigner::findAll(json_decode($pks)) as $model) {
            $model->delete();
        }


        if ($request->isAjax) {
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose' => true, 'forceReload' => true];
        } else {
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }

    }

    //VIP会员权限管理index
    public function actionAuthorityManagement()
    {
        $searchModel = new SysUserDesignerSearch();

        $dataProvider = $searchModel->search2(Yii::$app->request->queryParams, true, "");

        $t = PayUserDiscount::find()->select(['user_type', 'user_type_class', 'discount_rate', 'post_sales_service'])->distinct()->orderBy(['discount_rate' => SORT_DESC])->asArray()->all();
        $user_type = [];
        $ps_service = [0 => '含服务', 1 => '不含服务'];
        foreach ($t as $value) {
            if (!isset($user_type[$value['user_type']])) {
                $user_type[$value['user_type']] = [];
            }
            if (!in_array($value['user_type_class'], $user_type[$value['user_type']])) {
                $user_type[$value['user_type']][count($user_type[$value['user_type']])] = $value['user_type_class'] . '（折扣：' . $value['discount_rate'] . ' ' . $ps_service[$value['post_sales_service']] . '）';
            }
        }
        return $this->render('AuthorityManagement', [
            'user_type' => $user_type,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    //VIP会员权限管理提交数据处理
    public function actionDesignerAuthority()
    {
        $userType = UserInfo::find()->select(['user_type', 'user_type_class'])->where(['id' => Yii::$app->request->post('uid')])->asArray()->one();
        if ($userType["user_type"] == 3 && $userType['user_type_class'] == 5) {
            $isDesigner = true;
        } else {
            $isDesigner = false;
        }
        if (!\Yii::$app->user->can('user-designer')) {
            throw new ForbiddenHttpException(Yii::t('app', 'Sorry , You don\'t have permission'));
        }
        if (isset($_POST['uid']) && isset($_POST['q'])) {
            $uid = intval(Yii::$app->request->post('uid'));
            $model_userinfo = UserInfo::findOne(['id' => $uid]);
            $model = SysUserDesigner::findOne(['uid' => $uid]);
            if ($model->invite['invite_f'] == '888888') {
                $model_invite = UserInvite::findOne(['uid' => $uid]);
            } else {
                $model_invite = null;
            }

            if (Yii::$app->request->post('q') == 'get-info') {

                $user_def = [
                    '0' => '游客',
                    '1' => '普通用户',
                    '2' => 'VIP会员(申请中)',
                    '3' => '认证VIP会员',
                    '4' => '装饰公司',
                    '5' => '城市运营商',
                    '6' => '协会',
                    '7' => '服务商',
                    '8' => '内部员工'
                ];
                $t = ActiveRecord::findBySql('SELECT DISTINCT user_type FROM `pay_user_discount`')->asArray()->all();
                foreach ($t as $value) {
                    if (in_array($value['user_type'], [3, 4, 7])) {
                        $user_type_0[$value['user_type']] = $user_def[$value['user_type']];
                    }
                }
                return $this->renderAjax('_AMform', [
                    'user_type_0' => $user_type_0,
                    'model_invite' => $model_invite,
                    'model_userinfo' => $model_userinfo,
                    'isDesigner' => $isDesigner
                ]);
            } elseif (Yii::$app->request->post('q') == 'set-info') {
                $getPost = Yii::$app->request->post();
//                $userClass= UserInfo::find()->select(['user_type_class'])->where(['id'=>Yii::$app->request->post('uid')])->asArray()->one();
//                if($getPost['UserInfo']['user_type'] == 3 && $userClass['user_type_class'] != 5){
//                    $getPost['UserInfo']['user_type_class'] = 1;
//                }
                if ($getPost['UserInfo']['user_type'] != $model_userinfo->user_type) {
                    $getPost['UserInfo']['user_type_class'] = 1;
                }
                if ($model_userinfo->load($getPost) && $model_userinfo->validate() && $model_userinfo->save()) {
                    $userinfo_save = true;
                }
                $userInvite_save = null;
                if ($model_invite && $model_invite->load($getPost) && $model_invite->validate() && $model_invite->save()) {
                    $userInvite_save = true;
                }
                if ($userinfo_save && ($userInvite_save == null) || $userinfo_save && $userInvite_save) {
                    return $this->redirect(['sys-user-designer/authority-management']);
                } else {
                    echo '出错';
                }
            }
        }
    }

    //查询当天往前一年 消费满50w的用户 如即将过期，可给他续费
    public function actionVipContinute(){
        $searchModel = new SysUserDesignerSearch();
        $dataProvider = $searchModel->search_vippay_big();
        return $this->render('vip-continue', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
        
    }
    /**
     * 给vip用户续费
     */
    public function actionPostVipcontinue(){
        $post=Yii::$app->request->post();
         $idlist=$post['ids'];
         $count=count($idlist);
         //接收前端传递的自动续费用户，进行延期 
        if($count>0){
              for($i=0;$i<$count;$i++){
                   $uid=$idlist[$i];
                   $sys_user_designer=SysUserDesigner::findOne(["uid"=>$uid]);
                   $is_continue=LogVipContinue::findOne(["uid"=>$uid,"end_time">=time()]);
                   $user_pay_vip=UserPayVip::findOne(['user_id'=>$uid]);
                   if($sys_user_designer&&!$is_continue){
                       if(!empty($user_pay_vip)){
                               $user_pay_vip->end_time= $user_pay_vip->end_time+60*60*24*365;
                               $result=$user_pay_vip->save();
                               if($result){
                                   $log_vip_continue=new LogVipContinue();
                                   $log_vip_continue->user_id=$uid;
                                   $log_vip_continue->start_time=time();
                                   $log_vip_continue->end_time=time()+60*60*24*365;
                                   $result=$log_vip_continue->save();
                                   if($result){
                                       $return_result=array("code"=>'1',"msg"=> '再次续期成功!');
                                   }else{
                                       $return_result=array("code"=>'2',"msg"=> '添加log_vip_continue失败 !');
                                   }
                               }else{
                                   $return_result=array("code"=>'2',"msg"=> '修改user_pay_vip失败 !');
                               }
                               echo json_encode($return_result);exit();
                       }else{
                           $log_pay_vip=LogPayVip::find()->where(["uid"=>$uid,"state"=>1])->orderBy("starttime desc")->limit(1)->asArray()->all();
                           if(count($log_pay_vip)>0){
                               //修改用户类型
                               $user_type_class=$log_pay_vip[0]['user_type_class'];
                               $user_info=UserInfo::findOne($uid);
                               $user_info->user_type=$user_type_class;
                               $result=$user_info->save();
                               //新增user_pay_vip
                               $user_pay_vip=new UserPayVip();
                               $user_pay_vip->user_id=$uid;
                               $user_pay_vip->user_type_class=$user_type_class;
                               $user_pay_vip->start_time=time();
                               $user_pay_vip->end_time=time()+60*60*24*365;
                               $result=$user_pay_vip->save();
                               if($result){
                                   $log_vip_continue=new LogVipContinue();
                                   $log_vip_continue->user_id=$uid;
                                   $log_vip_continue->start_time=time();
                                   $log_vip_continue->end_time=time()+60*60*24*365;
                                   $result=$log_vip_continue->save();
                                   if($result){
                                       $return_result=array("code"=>'1',"msg"=> '该用户自动升级vip成功!');
                                   }else{
                                       $return_result=array("code"=>'2',"msg"=> '添加log_vip_continue失败 !');
                                   }
                               }else{
                                   $return_result=array("code"=>'2',"msg"=> '添加user_pay_vip失败 !');
                               }
                               echo json_encode($return_result);exit();
                           }else{
                               $return_result=array("code"=>'2',"msg"=> '该用户未支付会员费，不可续期!');
                               echo json_encode($return_result);exit();
                           }
                       }
                       
                   }
               }
        }else{
            $return_result=array("code"=>'2',"msg"=> '请选择用户!');
            echo json_encode($return_result);exit();
        }
        
        
    }
    /**
     * Finds the SysUserDesigner model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SysUserDesigner the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        $model = SysUserDesigner::find()->where("uid={$id}")->joinWith('userinfo')->one();
        //$model = SysUserDesigner::findOne($id)
        if ($model !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
